<template>
	<view class="body">
		<view class="header">
			<view class="userinfo">
				<view style="width: 80px">
					<image v-if="userInfo?.openId && userInfo?.avatarUrl" class="avatar" :src="userInfo.avatarUrl">
					</image>
					<image v-else class="avatar" src="../../static/images/avatar.png"></image>
				</view>
				<view style="flex: 1; padding: 0 30px">
					<u-button v-if="!userInfo?.openId" type="success" size="small"
						@click="authorization($store, $refs, activity)">微信登录</u-button>
					<view v-else class="info">
						{{ staffInfo?.orName ? staffInfo?.orName + `(${userInfo?.nickName})` : userInfo?.nickName }}
						<view style="font-size: 11px; font-weight: normal; margin-top: 5px">{{ userInfo.phone }}</view>
					</view>
				</view>
				<!-- <view style="width: 30px">
                    <uni-icons type="scan" size="26" style="margin-right: 20px" @click="scanCode"></uni-icons>
                </view> -->
			</view>

			<view class="vip">
				<uni-row>
					<uni-col span="8" class="item">
						<view class="num">{{ totalOrder }}</view>
						<view class="label">订单总数</view>
					</uni-col>
					<uni-col span="8" class="item">
						<view class="num">{{ finishOrder }}</view>
						<view class="label">订单总额</view>
					</uni-col>
					<uni-col span="8" class="item">
						<view class="num">{{ cpMones }}</view>
						<view class="label">我的足迹</view>
					</uni-col>
				</uni-row>
			</view>
		</view>

		<!-- <uni-section title="已购项目" type="line" padding="0" style="background-color: transparent">
			<uni-grid :column="3" :highlight="true" :showBorder="false" :square="false">
				<uni-grid-item>
					<view class="grid-box">
						<view style="display: flex; justify-content: space-between"
							@click="gotoPage(`/pages/my/my_service_item_current`)">
							<view style="margin-right: 10px; text-align: left">
								<Text style="color: #9a7d76">当前服务</Text>
							</view>
							<view style="margin-top: 10px; margin-left: 5px; text-align: right">
								<image src="../../static/images/customers.png" mode="aspectFit"
									style="width: 24px; height: 24px"></image>
							</view>
						</view>
					</view>
				</uni-grid-item>
				<uni-grid-item>
					<view class="grid-box">
						<view style="display: flex; justify-content: space-between"
							@click="gotoPage(`/pages/my/my_service_item`)">
							<view style="margin-right: 10px; text-align: left">
								<Text style="color: #9a7d76">已购服务</Text>
							</view>
							<view style="margin-top: 10px; margin-left: 5px; text-align: right">
								<image src="../../static/images/discount.png" mode="aspectFit"
									style="width: 24px; height: 24px"></image>
							</view>
						</view>
					</view>
				</uni-grid-item>
				<uni-grid-item>
					<view class="grid-box">
						<view style="display: flex; justify-content: space-between"
							@click="gotoPage(`/pages/my/my_service_item_use`)">
							<view style="margin-right: 10px; text-align: left">
								<Text style="color: #9a7d76">服务记录</Text>
							</view>
							<view style="margin-top: 10px; margin-left: 5px; text-align: right">
								<image src="../../static/images/order.png" mode="aspectFit"
									style="width: 24px; height: 24px"></image>
							</view>
						</view>
					</view>
				</uni-grid-item>
			</uni-grid>
		</uni-section> -->
		<view style="padding: 10px">
			<view class="list-box">
				<uni-list :border="false">
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconWallet" title="个人资料"
						rightText="查看" link="navigateTo" to="/pages/my/coupon" />
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconOrder" title="我的订单" rightText="查看"
						link="navigateTo" to="/pages/my/orders" />
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconGift" title="我的地址" rightText="查看"
						link="navigateTo" to="/pages/my/rebate" />
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconGift" title="我的分销" rightText="查看"
						@click="isOpened = true" :clickable="true" />
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconGift" title="会员账户"
						@click="getWxCode" :clickable="true" />
					<!-- <uni-list-item :show-extra-icon="true" showArrow v-if="!staffInfo?.orUuid" :extra-icon="iconStaff"
						title="员工登录" rightText="登录" link="navigateTo" to="/pages/staff/login" /> -->
					<!-- <uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconGift" title="老板页面" rightText="查看" link="navigateTo" to="/pages/boss/index" /> -->
				</uni-list>
			</view>

			<view class="list-box" v-if="staffInfo?.orUuid && staffInfo?.isBoss === false">
				<uni-list :border="false">
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconStaff" title="员工首页" rightText="查看"
						link="navigateTo" to="/pages/staff/index" />
				</uni-list>
			</view>

			<view class="list-box" v-if="staffInfo?.orUuid && staffInfo?.isBoss === true">
				<uni-list :border="false">
					<uni-list-item :show-extra-icon="true" showArrow :extra-icon="iconBoss" title="老板首页" rightText="查看"
						link="navigateTo" to="/pages/boss/index" />
				</uni-list>
			</view>
		</view>

		<view>
			<u-modal :show="isOpened" confirmText="关闭" width="250" @confirm="isOpened = false">
				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="userInfo.ciUuid" :options="{ margin: 10 }"></uqrcode>
				<canvas width="300" height="300" canvas-id="qrcode"></canvas>
			</u-modal>
		</view>

		<u-modal :show="isOpened1" confirmText="保存到相册" cancelText="关闭显示" showCancelButton="true" width="250"
			@confirm="saveImg()" @cancel="isOpened1 = false">
			<image class="avatar" style="width: 200px; height: 200px" :src="filePath"></image>
		</u-modal>

		<!-- 授权微信手机号弹窗 -->
		<uni-popup ref="popup" background-color="#fff">
			<view style="padding: 30px">
				<button type="primary" open-type="getPhoneNumber"
					@getphonenumber="(e) => decryptPhoneNumber(e, $store, $refs, appid, activity)">微信一键授权</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapGetters
	} from "vuex";
	import {
		getWxCode,
		getWxPhoneNumber,
		getCustomerByCiPhon,
		createCustomers,
		createPlatformConsumerInfo,
		createCustomerLoginRelationship,
		updateCustomerByCiUuid,
		mergeGuestToCustomer,
		getOrderByCiUuid,
		getItemRebateByCiUuid,
		getConsumerHomePage,
	} from "../../utils/api";
	import {
		userAuthorization,
		numberFormat
	} from "../../utils/helper";

	export default {
		data() {
			return {
				cpMones: 0,
				finishOrder: 0,
				totalOrder: 0,

				iconWallet: {
					color: "#6699ff",
					size: "22",
					type: "wallet-filled",
				},
				iconStaff: {
					color: "#6699ff",
					size: "22",
					type: "person-filled",
				},
				iconGift: {
					color: "#6699ff",
					size: "22",
					type: "gift-filled",
				},
				iconOrder: {
					color: "#6699ff",
					size: "22",
					type: "list",
				},
				iconBoss: {
					color: "#6699ff",
					size: "22",
					type: "contact-filled",
				},
				isOpened: false,
				isOpened1: false,
				filePath: "",
			};
		},

		onLoad() {
			this.getConsumerHomePage();
			if (this.userInfo?.openId && !this.userInfo?.phone) {
				this.$refs.popup.open("bottom");
			}
		},

		onShow() {
			this.getConsumerHomePage();
		},

		computed: {
			...mapGetters({
				appid: "globalInfo/appid",
				userInfo: "personInfo/userInfo",
				staffInfo: "personInfo/staffInfo",
				activity: "activityInfo/activity",
			}),
		},

		watch: {
			userInfo: {
				handler(newValue, oldValue) {
					if (newValue?.openId && !newValue?.phone) {
						this.$refs.popup.open("bottom");
					}
					if (newValue?.openId && newValue?.phone) {
						this.$refs.popup && this.$refs.popup.close();
						this.getConsumerHomePage();
					}
				},
				immediate: true,
				deep: true,
			},
		},
		methods: {
			...mapMutations({}),

			gotoPage(url) {
				uni.navigateTo({
					url,
				});
			},

			async getWxCode() {
				const fs = uni.getFileSystemManager();
				const filePath = `${wx.env.USER_DATA_PATH}/888.png`;
				try {
					fs.accessSync(filePath);
				} catch (e) {
					let res = await getWxCode({
						appid: this.appid,
						page: "pages/staff/login",
						scene: "staff",
					});
					if (res) {
						// 将返回的图片buffer生成图片，并保存至临时用户文件中
						fs.writeFileSync(filePath, res, "base64");
					}
				}
				this.filePath = filePath;
				this.isOpened1 = true;
			},

			saveImg() {
				uni.saveImageToPhotosAlbum({
					filePath: this.filePath,
					success: (res) => {
						uni.showToast({
							title: "已保存到相册",
							icon: "success",
							duration: 3000,
						});
					},
					fail: async (err) => {
						if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
							const ret = await uni.getSetting();
							if (ret.authSetting["scope.writePhotosAlbum"]) {
								uni.showToast({
									title: "已授权",
									icon: "success",
								});
							}
							if (ret.authSetting["scope.writePhotosAlbum"] == false) {
								uni.showModal({
									title: "提示",
									content: "图片保存失败，请前往设置页面允许保存相册",
									confirmColor: "#8C5CDD",
									success: function(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													console.log(res);
												},
											});
										}
										if (res.cancel) {
											uni.showToast({
												title: "取消",
												icon: "error",
											});
										}
									},
								});
							}
						}
					},
				});
			},

			authorization: async ($store, $refs, activity) => {
				const user = await userAuthorization(activity.gpUuid);
				if (user) {
					$store.dispatch("personInfo/save", {
						userInfo: user,
					});
					if (!user?.phone) $refs.popup.open("bottom");
				}
			},

			decryptPhoneNumber: async (e, $store, $refs, appid, activity) => {
				$refs.popup.close();

				if (e.detail.errMsg !== "getPhoneNumber:ok") return;

				let userInfo = uni.getStorageSync("userInfo"); // 用户信息

				let brwseData = {
					ciUuid: userInfo.ciUuid,
				};

				const phoneInfo = await getWxPhoneNumber({
					appid,
					...e.detail,
				});
				if (!phoneInfo?.phone_info?.phoneNumber)
					return uni.showToast({
						title: "没有获取到当前客户的手机号",
						icon: "none",
						duration: 2000,
					});

				let resCust = await getCustomerByCiPhon({
					ciPhon: phoneInfo.phone_info.phoneNumber,
				});

				let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
				let staffId = uni.getStorageSync("staffId") || ""; // 员工ID

				if (!resCust?.ciUuid) {
					let data = {
						ciPhon: phoneInfo.phone_info.phoneNumber,
						ciAvat: userInfo.avatarUrl,
						ciFrom: "新客",
						ciCity: userInfo.city,
						ciPrin: userInfo.province,
						ciAlia: userInfo.nickName,
						openId: userInfo.openId,
						appId: appid,
						orUuid: staffId || null,
					};

					let resId = await createCustomers(data);

					if (resId) {
						userInfo.ciUuid = resId?.ciUuid;
						userInfo.phone = phoneInfo.phone_info.phoneNumber;
						userInfo.isNew = true;
						userInfo.isLogin = true;

						$store.dispatch("personInfo/save", {
							userInfo,
						});

						createPlatformConsumerInfo({
							ciAlia: userInfo.nickName,
							ciAvat: userInfo.avatarUrl,
							ciPhon: userInfo.phone,
							appId: appid,
							openId: userInfo.openId,
						});

						let rlData = {
							gpUuid: activity.gpUuid,
							ciUuid: userInfo.ciUuid,
							clTime: new Date().getUTCTime(),
						};

						if (shareId) rlData.scUuid = shareId;
						if (staffId) rlData.orUuid = staffId;

						if (staffId || shareId) {
							createCustomerLoginRelationship(rlData);
						}
					}
				} else {
					let data = {
						ciUuid: resCust?.ciUuid,
						ciPhon: phoneInfo.phone_info.phoneNumber,
						ciAvat: userInfo.avatarUrl,
						ciCity: userInfo.city,
						ciPrin: userInfo.province,
						ciAlia: userInfo.nickName,
						openId: userInfo.openId,
						appId: appid,
					};

					let res1 = await updateCustomerByCiUuid(data);

					if (res1) {
						userInfo.ciUuid = resCust?.ciUuid;
						userInfo.phone = phoneInfo.phone_info.phoneNumber;
						userInfo.isNew = resCust?.ciFrom === "新客" ? true : false;
						userInfo.ciName = resCust?.ciName;
						userInfo.isLogin = true;

						$store.dispatch("personInfo/save", {
							userInfo,
						});

						createPlatformConsumerInfo({
							ciAlia: userInfo.nickName,
							ciAvat: userInfo.avatarUrl,
							ciPhon: userInfo.phone,
							appId: appid,
							openId: userInfo.openId,
						});

						let rlData = {
							gpUuid: activity.gpUuid,
							ciUuid: userInfo.ciUuid,
							clTime: new Date().getUTCTime(),
						};
						if (shareId) rlData.scUuid = shareId;
						if (staffId) rlData.orUuid = staffId;
						if (staffId || shareId) {
							createCustomerLoginRelationship(rlData);
						}
					}
				}

				brwseData.ciUuidNew = userInfo.ciUuid;
				brwseData.ciAlia = userInfo.nickName;
				brwseData.ciType = userInfo.isNew ? "新客" : "老客";

				mergeGuestToCustomer(brwseData);
			},

			async getConsumerHomePage() {
				if (this.userInfo.ciUuid && this.activity.gpUuid) {
					let res = await getConsumerHomePage({
						ciUuid: this.userInfo.ciUuid,
						gpUuid: this.activity.gpUuid,
					});
					if (res) {
						this.totalOrder = res.orders?.length || 0;
						this.cpMones = res.cpMones; // 奖励红包
						this.finishOrder = res.orders?.filter((item) => item.soStat === "已支付")?.length || 0;
					}
				}
			},

			scanCode() {
				const that = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ["qrCode"],
					success: async function(res) {
						console.log(res);
						uni.showToast({
							title: res,
						});
					},
				});
			},
		},
	};
</script>

<style lang="scss">
	page {
		margin-bottom: 10px;
		background-color: #eee;
	}
</style>

<style lang="scss" scoped>
	page {
		margin-bottom: 10px;
	}

	.header {
		padding: 80px 10px 0 10px;
		background-color: #EEC900;

		.userinfo {
			display: flex;
			padding: 10px 15px 10px 24px;
			background-color: #fff;
			border-radius: 5px;
			margin-top: 20px;
			align-items: center;
		}

		.avatar {
			height: 60px;
			width: 60px;
			border-radius: 50%;
		}

		.info {
			font-weight: 600;
			font-size: 14px;
			margin-top: 10px;
		}

		.vip {
			color: #fff;
			padding: 20px 0;

			.num {
				margin-top: 5px;
				text-align: center;
				font-size: 20px;
			}

			.label {
				text-align: center;
				font-size: 12px;
				margin-top: 5px;
			}
		}
	}

	.list-box {
		padding: 2px;
		border-radius: 6px;
		box-shadow: 0 0px 6px 1px rgba(165, 165, 165, 0.2);
		background-color: #fff;
		margin-bottom: 10px;
	}

	.grid-box {
		// border-radius: 10px;
		box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.2);
		background-color: #eee;
		padding: 10px 20px;
		margin: 0 5px 10px 10px;
	}

	.grid {
		border-radius: 6px;
	}
</style>